package com.ys.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;

//工具类
public final class ToolUtil {


	/**
	 * 去重List
	 * subDataArray：要去重的原数据
	 * groupCondition：去重的条件,多个条件用字符串形式拼接（例如：e->e.get("id").toString()+e.get("name").toString()）
	 */
	public static List<Map<String, Object>> groupsByList(List<Map<String, Object>> dataList, Function<Map<String, Object>,String> groupCondition) {

		//去重
		Map<String, List<Map<String, Object>>> groupsByStr = dataList.stream().collect(Collectors.groupingBy(e->groupCondition.apply(e)));
		List<Map<String, Object>> resList = new ArrayList<>();
		//遍历，填入去重的信息
		groupsByStr.forEach((k, v) -> resList.add(v.get(0)));
		return resList;
	}


	/**
	 * 去重JSONArray
	 * dataArray：要去重的原数据
	 * groupCondition：去重的条件,多个条件用字符串形式拼接（例如：e->e.get("id").toString()+e.get("name").toString()）
	 */
	public static List<Map<String, Object>> groupsByJSONArray(JSONArray dataArray, Function<Map<String, Object>,String> groupCondition) {
		List<Map<String, Object>> dataList = new ArrayList<>();
		if(dataArray!=null && dataArray.size()>0) {
			for (int i = 0; i < dataArray.size(); i++) {
				JSONObject jsonObject = dataArray.getJSONObject(i);
				Map<String, Object> paramsNewByRecord = new HashMap<>();
				for (String key : jsonObject.keySet()) {
					paramsNewByRecord.put(key, jsonObject.get(key));
				}
				dataList.add(paramsNewByRecord);
			}
		}
		return groupsByList(dataList,groupCondition);
	}


	/**
	 *JSONArray转list
	 * dataArray：原数据
	 */
	public static List<Map<String, Object>> jsonArrayToList(JSONArray dataArray) {

	//public static List<Map<String, Object>> changeJSONArrayToList(JSONArray dataArray) {

		List<Map<String, Object>> dataList = new ArrayList<>();
		if(dataArray!=null && dataArray.size()>0) {
			for (int i = 0; i < dataArray.size(); i++) {
				JSONObject jsonObject = dataArray.getJSONObject(i);
				Map<String, Object> paramsNewByRecord = new HashMap<>();
				for (String key : jsonObject.keySet()) {
					paramsNewByRecord.put(key, jsonObject.get(key));
				}
				dataList.add(paramsNewByRecord);
			}
		}
		return dataList;
	}


}
